package com.imooc.bilibili.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.imooc.bilibili.dao.DanMuDao;
import com.imooc.bilibili.domain.Danmu;
import com.mysql.cj.util.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ProjectName imooc-bilibili
 *
 * @author xieyucan
 * <br>CreateDate 2022/10/26 11:49
 */
@Service(value = "danMuService")
public class DanMuService {

    private static final String DANMU_KEY="dm-key";

    @Resource
    private DanMuDao danMuDao;

    @Resource
    private RedisTemplate redisTemplate;


    @Async("getAsyncExecutor")
    public void asyncAddDanMu(Danmu danmu) {
        danMuDao.addDanMu(danmu);
    }

    /**
     * 将弹幕存储到redis中
     * @param danmu
     */
    public void addDanMuToRedis(Danmu danmu) {
        String key=DANMU_KEY+danmu.getVideoId();
        String value=(String) redisTemplate.opsForValue().get(key);
        List<Danmu> list = new ArrayList<>();
        if(StringUtils.isNullOrEmpty(value)){
            list=JSONArray.parseArray(value, Danmu.class);
        }
        list.add(danmu);
        redisTemplate.opsForValue().set(key, JSONObject.toJSONString(list));
    }

    public List<Danmu> getDanMuList(Integer videoId,String startTime,String endTime) throws ParseException {
        //先从redis中获取
        String key=DANMU_KEY+videoId;
        String value=(String) redisTemplate.opsForValue().get(key);
        List<Danmu> list;
        if(!StringUtils.isNullOrEmpty(value))
        {
            list=JSONArray.parseArray(value,Danmu.class);
            if(!StringUtils.isNullOrEmpty(startTime) && !StringUtils.isNullOrEmpty(endTime))
            {
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date startDate = simpleDateFormat.parse(startTime);
                Date endDate = simpleDateFormat.parse(endTime);
                List<Danmu> danmuList=new ArrayList<>();
                for(Danmu danmu:list)
                {
                    Date createTime = danmu.getCreateTime();
                    if(createTime.before(endDate) && createTime.after(startDate))
                    {
                        danmuList.add(danmu);
                    }
                }
                list=danmuList;
            }

        }
        //如果获取不到，则查询数据库，然后再存储进redis中
        else {
            Map<String,Object> params=new HashMap<>();
            params.put("video",videoId);
            params.put("startTime",startTime);
            params.put("endTime",endTime);
            list=danMuDao.getDanMuList(params);
            redisTemplate.opsForValue().set(key,JSONObject.toJSONString(list));
        }
        return list;
    }
}
